package main

import "fmt"

func Add(a int, b int) int {
	return a + b
}

func divide(a int, b int) (int, int) {
	return a / b, a % b
}

func add1(a, b int) (result int) {
	result = a + b
	return // 也可以写 return result
}

func sum(nums ...int) int {
	total := 0
	for _, v := range nums {
		total += v
	}

	return total
}

func calc(a, b int, op func(int, int) int) int {
	return op(a, b)
}

func counter() func() int {
	i := 0
	return func() int {
		i++
		return i
	}
}

func factorial(n int) int {
	if n == 0 {
		return 1
	}
	return n * factorial(n-1)
}

func main() {

	// 函数的使用
	result := Add(1, 2)
	fmt.Println("the result is: ", result)

	// 多返回值
	q, r := divide(10, 3)
	fmt.Println("q=", q, "r=", r)

	// 命名返回值
	result = add1(1, 2)
	fmt.Println("the result is: ", result)

	// 可变参数
	res := sum(1, 2, 3, 4, 5)
	fmt.Println("sum = ", res)
	res = sum(1, 2, 3, 4, 5, 6, 7, 8, 9)
	fmt.Println("sum = ", res)

	// 把函数作为参数进行返回
	item := calc(3, 5, Add)
	fmt.Printf("item type is %T\n", item)
	fmt.Println("item = ", item)

	// 匿名函数
	add := func(a, b int) int {
		return a + b
	}
	fmt.Println("add = ", add(1, 2))

	// 闭包
	c := counter()
	fmt.Println("c = ", c()) // 12.9
	fmt.Println("c = ", c()) // 2

	// 小案例
	fmt.Println("5的阶乘是 ", factorial(5)) // 输出120

}
